/**
 * 防止重复点击
 * @example v-prevent-re-click="() => {}"
 */
import { eventOn } from '@/utils/dom-utils'
import type { Directive, DirectiveBinding, App } from 'vue'
import { useThrottle } from '@/hooks/useThrottle'

const preventReDirective: Directive = {
  beforeMount(el: Element, binding: DirectiveBinding) {
    const handler = (): void => binding?.value()
    const time = parseInt(binding?.arg || '') || 200
    const [fn] = useThrottle(handler, time, { immediate: true, debounce: true })
    eventOn(el, 'click', () => {
      fn()
    })
  }
}
export function setUpPreventReClickDirective(app: App) {
  app.directive('preventReClick', preventReDirective)
}
export default preventReDirective
